package com.huang.common.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hqy
 * @date 2022年06月20日 20:15
 */
@Configuration
public class OauthFeignConfig implements RequestInterceptor {

    private static final String CLIENT_TOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9" +
            ".eyJzY29wZSI6WyJhbGwiXSwiZXhwIjozODAzMjExNzI1LCJqdGkiOiJmYjgzZGU2YS02NTYwLTQ5YWItODI0ZS03NTllNjdmNmQxMjMiLCJjbGllbnRfaWQiOiJwb3dlciJ9.Fo8ajcaGHAW7PjfKvK" +
            "_3ssjaGM2Yg3fdhc6NQKtULpAWhrjSqpAx8083uXLZRQiPf45p8" +
            "_ulVvwCfmlbSwtXerhex1c-IL8eJDxre1vkpLSthjKHO9vXaEtDlzhjQWC4JYxCovU" +
            "_Fu4qZv1nJebZgOrOeeysYTKfL7bKmJso6WglbsJAJbuUMvgOnHOG41QUfAMkuhWTQLORCiph4AJ6RWzKbz" +
            "_LQYQvBWxvro2q0Cp-RBKvYcG2yptZKEZ7zUPhhzkA5alS0WYwvCpaMsf6Y9kkC0VkBhgRmhF1F3" +
            "_oIegSl144T3w5kWbarH1GVHBlZU34A1Uz5Esb3DrgHq5O_g";

    /**
     * 服务间的调用   在请求头中设置token
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        //获取request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //从请求头中获取token
        String authorization = request.getHeader("Authorization");
        if(StringUtils.hasText(authorization)){
            template.header("Authorization",authorization);
        }else{

            //使用客户端模式产生一个token  放入feign调用的请求头中
            template.header("Authorization","bearer " + CLIENT_TOKEN);
        }

    }
}
